import express, { Request, Response } from "express";
import multer from "multer";
import { parseExcelFile } from "./utils/parseExcelFile";
import { YundocApi } from './utils/yundocRequest'
// const iconv = require('iconv-lite');
const app = express();
const PORT = process.env.PORT || 3000;
const appId: any = process.env.AK
const appKey: any = process.env.SK
// 处理跨域请求
app.use((req: Request, res: Response, next: any) => {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
	res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
	if (req.method == "OPTIONS") {
		res.sendStatus(200);
	} else {
		next();
	}
});
// 静态资源目录
app.use(express.static("uploads"));
app.get("/", (req: Request, res: Response) => {
	res.send("Hello, World!");
});

// 上传文件相关接口及逻辑
const storage = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, "uploads/");
	},
	filename: function (req, file, cb) {
		file.originalname = Buffer.from(file.originalname, "latin1").toString(
			"utf8"
		);
		cb(null, file.originalname);
	},
});
const upload = multer({ storage });
app.post("/uploadAndParse", upload.single("file"), (req: Request, res: Response) => {
	// 上传后进行文件解析
	const filePath = req?.file?.path;
	let list = parseExcelFile(filePath as string)
	console.log("list -> " + JSON.stringify(list));
	if (list instanceof Object && !(list instanceof Array) && !list.isPass) {
		// 获取错误信息，返回给前端
		let errMessage = list.errMessage;
		res.json({
			code: 500,
			message: "上传失败，" + errMessage,
			data: []
		})
		return
	}
	// 超过1000条则提示错误
	if (list instanceof Array && list.length > 1000) {
		res.json({
			code: 500,
			message: "上传失败，数据条数超过1000条",
			data: []
		})
	} else {
		/**
		 * 获取根部门
		 */
		let request = new YundocApi();
		let data: any = request.apiDepartment();
		let depts_id = data.data.id;

		/**
		 * 获取子部门列表
		 */
		let resData: any = request.apiBranch(depts_id);
		let dataList = resData.data.depts;
		//表内数据和获取的子部门列表进行对比判断是否存在子部门
		let dept_id//部门id
		let account_id //创建用户
		dataList.foreach((dept: { name: any; parent_id: number; source: any; third_platform_id: any; third_union_id: any; }) => {
			list.foreach((list: { dept: any; name: any; password: any; username: any; phone: any; email: any; }) => {
				if (dept.name === list.dept) {
					console.log('该部门已存在');
				} else {
					//不存在新增子部门
					dept_id = dept.parent_id
					//获取account_id
					let accountResData: any = request.createUser({
						name: list.name,
						password: list.password,
						username: list.username,
						phone: list.phone,
						email: list.email,
						dept: list.dept,
					});

					account_id = accountResData.data.account_id;
				}
			});
		});


		//添加账户到部门
		let users: any = request.addAccount(dept_id as any, account_id as any, {
			"set_def_dept": true,
			"weight": 0
		})
		if (users.code === 0) {
			//启用企业成员
			let newUser = request.enterpriseMembers({
				"account_ids": [
					1
				]
			})
		} else {
			console.log(users.msg);
		}

		res.json({
			code: 200,
			message: "上传成功",
			data: list
		});
	}
});
// 同步全量数据
app.post("/syncData", (req: Request, res: Response) => {
	res.json({
		code: 200,
		message: "同步成功",
		data: []
	});
});
// 清除数据
app.post("/clearData", (req: Request, res: Response) => {
	res.json({
		code: 200,
		message: "清除成功",
		data: []
	});
});

app.listen(PORT, () => {
	console.log(`Server is running on port ${PORT}`);
});